#include "MainWindow.h"
//#include "MyModel.h"

const int ROWS = 2;
const int COLS = 3;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
//    tableView = new QTableView(this);
    treeView = new QTreeView(this);
    setCentralWidget(treeView);
    standarModel = new QStandardItemModel;
//    QList<QStandardItem *> preparedRow = prepareRow("1er", "2do", "3ro");
//    QStandardItem *item = standarModel->invisibleRootItem();
    QStandardItem *rootNode = standarModel->invisibleRootItem();

    QStandardItem *americanItem =   new QStandardItem("America");
    QStandardItem *canadianItem =   new QStandardItem("Canada");
    QStandardItem *usaItem      =   new QStandardItem("Usa");
    QStandardItem *bostonItem   =   new QStandardItem("Boston");
    QStandardItem *europeItem   =   new QStandardItem("Europe");
    QStandardItem *italyItem    = new QStandardItem("Italy");
    QStandardItem *romeItem     =   new QStandardItem("Rome");
    QStandardItem *veronaItem   =   new QStandardItem("Verona");

    rootNode->appendRow(americanItem);
    rootNode->appendRow(europeItem);
    americanItem->appendRow(canadianItem);
    americanItem->appendRow(usaItem);
    usaItem->appendRow(bostonItem);
    europeItem->appendRow(italyItem);
    italyItem->appendRow(romeItem);
    italyItem->appendRow(veronaItem);
//    item->appendRow(preparedRow);
//    QList<QStandardItem *> secondRow = prepareRow("111", "222", "333");
//    preparedRow.first()->appendRow(secondRow);
    treeView->setModel(standarModel);
    treeView->expandAll();
//    QAbstractTableModel *myModel = new MyModel(this);
//    tableView->setModel(myModel);

//    connect(myModel, SIGNAL(editCompleted(const QString &)), this, SLOT(showWindowTitle(const QString &)));
    QItemSelectionModel *selectionModel = treeView->selectionModel();
    connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChangedSlot(const QItemSelection &,const QItemSelection &)));
}

QList<QStandardItem *> MainWindow::prepareRow(const QString &first, const QString &second, const QString &third)
{
    QList<QStandardItem *> rowItems;
    rowItems << new QStandardItem(first);
    rowItems << new QStandardItem(second);
    rowItems << new QStandardItem(third);
    return rowItems;
//    return QList<QStandardItem *>();
}

void    MainWindow::showWindowTitle(const QString &title)
{
    qDebug() << "showWindowTitle";
    setWindowTitle(title);
}

void    MainWindow::selectionChangedSlot(const QItemSelection &, const QItemSelection &)
{
    const QModelIndex index = treeView->selectionModel()->currentIndex();
    QString selectedText = index.data(Qt::DisplayRole).toString();
    int hLevel = 1;
    QModelIndex seekRoot = index;
    while (seekRoot != QModelIndex())
    {
        seekRoot = seekRoot.parent();
        hLevel++;
    }
    QString showString = QString("%1 - Nivel %2").arg(selectedText).arg(hLevel);
    showWindowTitle(showString);
}
